package io.gitee.devaper.starlight.security.handler

import io.gitee.devaper.starlight.common.entity.vo.*
import io.gitee.devaper.starlight.common.util.*
import io.gitee.devaper.starlight.security.constant.*
import io.gitee.devaper.starlight.security.exception.*
import jakarta.servlet.http.*
import org.springframework.context.MessageSource
import org.springframework.context.MessageSourceAware
import org.springframework.security.authentication.*
import org.springframework.security.core.*
import org.springframework.security.core.userdetails.*
import org.springframework.security.web.authentication.AuthenticationFailureHandler
import org.springframework.stereotype.Component

/**
 * 认证失败处理器
 */
@Component
open class DefaultAuthenticationFailureHandler : AuthenticationFailureHandler, MessageSourceAware {
    override fun onAuthenticationFailure(
        request: HttpServletRequest,
        response: HttpServletResponse,
        exception: AuthenticationException
    ) {
        val msg = when(exception) {
            is UsernameNotFoundException -> messageSource.getMessage(MS_AUTHENTICATION_FAILURE, null, request.locale)
            is BadCredentialsException -> messageSource.getMessage(MS_AUTHENTICATION_FAILURE, null, request.locale)
            is UsernameFormatMismatchException -> messageSource.getMessage(
                MS_AUTHENTICATION_VALIDATION_USERNAME_FORMAT_MISMATCH, null, request.locale)
            is PasswordFormatMismatchException -> messageSource.getMessage(
                MS_AUTHENTICATION_VALIDATION_PASSWORD_FORMAT_MISMATCH, null, request.locale)
            else -> messageSource.getMessage(MS_AUTHENTICATION_FAILURE_UNKNOWN, arrayOf(exception.message), request.locale)
        }
        response.write(data = ApiResult.error(msg), request = request)
    }

    private lateinit var messageSource: MessageSource

    override fun setMessageSource(messageSource: MessageSource) {
        this.messageSource = messageSource
    }
}